package com.digua.base.util

import android.os.Handler
import android.os.Looper
import android.os.Message

object HandlerUtils {

    fun getMainHandler(handleMessage: ((Message) -> Unit)? = null): Handler {
        return object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                handleMessage?.let { handleMessage(msg) }
            }
        }
    }

    /**
     * @param handler
     * @param what
     * @param isCover 是否覆盖执行
     */
    fun sendEmpty(handler: Handler?, what: Int, isCover: Boolean = false) {
        if (handler == null) return
        if (isCover) {
            handler.removeMessages(what)
        } else if (handler.hasMessages(what)) {
            return
        }
        handler.sendEmptyMessage(what)
    }

    /**
     * @param handler
     * @param what
     * @param data
     * @param isCover 是否覆盖执行
     */
    fun sendMessage(handler: Handler?, what: Int, data: Any, isCover: Boolean = false) {
        if (handler == null) return
        if (isCover) {
            handler.removeMessages(what)
        } else if (handler.hasMessages(what)) {
            return
        }
        val msg = Message()
        msg.what = what
        msg.obj = data
        handler.sendMessage(msg)
    }

    /**
     * @param handler
     * @param what
     * @param isCover 是否覆盖执行
     */
    fun sendEmptyDelayed(handler: Handler?, what: Int, delayMillis: Long, isCover: Boolean = false) {
        if (handler == null) return
        if (isCover) {
            handler.removeMessages(what)
        } else if (handler.hasMessages(what)) {
            return
        }
        handler.sendEmptyMessageDelayed(what, delayMillis)
    }

    /**
     * @param handler
     * @param what
     * @param data
     * @param delayMillis
     * @param isCover 是否覆盖执行
     */
    fun sendMessageDelayed(handler: Handler?, what: Int, data: Any, delayMillis: Long, isCover: Boolean = false) {
        if (handler == null) return
        if (isCover) {
            handler.removeMessages(what)
        } else if (handler.hasMessages(what)) {
            return
        }
        val msg = Message()
        msg.what = what
        msg.obj = data
        handler.sendMessageDelayed(msg, delayMillis)
    }

    fun removeMsgs(handler: Handler?, vararg whats: Int) {
        if (handler == null) return
        for (what in whats) handler.removeMessages(what)
    }
}